package org.jsola.hr.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import org.jsola.core.Page;
import org.jsola.exception.ParamException;
import org.jsola.hr.common.ExampleKit;
import org.jsola.hr.constant.CrmMemberJurisdictionType;
import org.jsola.hr.constant.CrmOperationType;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dao.ICrmCustomerInfoDAO;
import org.jsola.hr.dto.CrmCustomerDistributionRecordAddDTO;
import org.jsola.hr.dto.CrmCustomerInfoAddDTO;
import org.jsola.hr.dto.CrmCustomerInfoUpdateDTO;
import org.jsola.hr.dto.CrmOperationRecordAddDTO;
import org.jsola.hr.entity.CrmCustomerInfoDO;
import org.jsola.hr.query.CrmCustomerInfoQuery;
import org.jsola.hr.query.CrmMemberQuery;
import org.jsola.hr.query.CrmMemberRelationQuery;
import org.jsola.hr.service.*;
import org.jsola.hr.vo.*;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 客户详情表
 *
 * @author zhr
 */
@Service("hrCrmCustomerInfoServiceImpl")
public class CrmCustomerInfoServiceImpl implements ICrmCustomerInfoService {

    @Autowired
    private ICrmCustomerInfoDAO crmCustomerInfoDAO;
    @Autowired
    private ICrmCustomerDistributionRecordService crmCustomerDistributionRecordService;
    @Autowired
    private ICrmMemberService crmMemberService;
    @Autowired
    private ICrmOperationRecordService crmOperationRecordService;
    @Autowired
    private ICrmMemberRelationService crmMemberRelationService;

    @Override
    public CrmCustomerInfoVO queryCustomerInfo(CrmCustomerInfoQuery crmCustomerInfoQuery, TokenUser tokenUser) {
        CrmCustomerInfoVO crmCustomerInfoVO = selectById(crmCustomerInfoQuery.getCustomerId(), tokenUser.getSiteId());
        if (crmCustomerInfoQuery.getIsPublic() != null && crmCustomerInfoQuery.getIsPublic()) {
            StringBuilder stringBuilder = new StringBuilder(crmCustomerInfoVO.getPhone());
            crmCustomerInfoVO.setPhone(stringBuilder.replace(3, 7, "****").toString());
        }
        return crmCustomerInfoVO;
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public CrmCustomerInfoVO saveCustomer(CrmCustomerInfoAddDTO crmCustomerInfoAddDTO, TokenUser tokenUser) {
        checkRepeat(crmCustomerInfoAddDTO.to(CrmCustomerInfoDO.class), tokenUser);
        CrmMemberQuery crmMemberQuery = new CrmMemberQuery();
        crmMemberQuery.setUserId(tokenUser.getUserId());
        List<CrmMemberListVO> select = crmMemberService.select(crmMemberQuery, tokenUser.getSiteId());
        if (CollectionUtil.isEmpty(select)) {
            // throw new ParamException("你还没有增加客户的权限");
            return null;
        }
        if (crmCustomerInfoAddDTO.getType() != null && crmCustomerInfoAddDTO.getType() == 2) {
            crmCustomerInfoAddDTO.setSigningTime(new Date());
            crmCustomerInfoAddDTO.setIsSign(true);
        }
        crmCustomerInfoAddDTO.setSourceName(tokenUser.getUserName());
        if (!crmCustomerInfoAddDTO.getIsPublic()) {
            crmCustomerInfoAddDTO.setDistributeName(tokenUser.getUserName());
            crmCustomerInfoAddDTO.setUserId(tokenUser.getUserId());
            crmCustomerInfoAddDTO.setMemberId(select.get(0).getId());
            crmCustomerInfoAddDTO.setMemberName(tokenUser.getUserName());
        }
        crmCustomerInfoAddDTO.setSourceUserId(tokenUser.getUserId());
        crmCustomerInfoAddDTO.setSourceName(tokenUser.getUserName());
        crmCustomerInfoAddDTO.setSourceType(2);
        CrmCustomerInfoVO customerInfoVO = save(crmCustomerInfoAddDTO, tokenUser);
        //操作记录
        CrmOperationRecordAddDTO crmOperationRecordAddDTO = new CrmOperationRecordAddDTO();
        crmOperationRecordAddDTO.setCustomerId(customerInfoVO.getId());
        crmOperationRecordAddDTO.setOperationName(tokenUser.getUserName());
        crmOperationRecordAddDTO.setOperationType(CrmOperationType.ADD.getValue());
        crmOperationRecordAddDTO.setRecordInfo("新增" + customerInfoVO.getName() + "客户");
        crmOperationRecordService.save(crmOperationRecordAddDTO, tokenUser);
        //分配记录
        CrmCustomerDistributionRecordAddDTO crmCustomerDistributionRecordAddDTO = new CrmCustomerDistributionRecordAddDTO();
        crmCustomerDistributionRecordAddDTO.setCustomerId(customerInfoVO.getId());
        crmCustomerDistributionRecordAddDTO.setDistributionInfo("由" + tokenUser.getUserName() + "新增");
        crmCustomerDistributionRecordService.save(crmCustomerDistributionRecordAddDTO, tokenUser);
        return customerInfoVO;
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public Page<CrmCustomerInfoListVO> getCustomerPage(CrmCustomerInfoQuery crmCustomerInfoQuery, TokenUser tokenUser) {
        if (!StringUtils.isEmpty(crmCustomerInfoQuery.getMemberId())) {
            CrmCustomerInfoQuery crmCustomerInfoQuery1 = new CrmCustomerInfoQuery();
            crmCustomerInfoQuery1.setPageSize(crmCustomerInfoQuery.getPageSize());
            crmCustomerInfoQuery1.setPageNo(crmCustomerInfoQuery.getPageNo());
            crmCustomerInfoQuery1.setMemberId(crmCustomerInfoQuery.getMemberId());
            crmCustomerInfoQuery1.setType(crmCustomerInfoQuery.getType());
            return selectPage(crmCustomerInfoQuery, tokenUser.getSiteId());
        }
        List<String> memberIdList = new ArrayList<>();
        CrmMemberQuery crmMemberQuery = new CrmMemberQuery();
        crmMemberQuery.setUserId(tokenUser.getUserId());
        List<CrmMemberListVO> select = crmMemberService.select(crmMemberQuery, tokenUser.getSiteId());
        if (select == null || select.size() == 0) {
            // throw new ParamException("当前用户未配置权限");
            return null;
        }
        if (crmCustomerInfoQuery.getIsPublic()) {
            CrmCustomerInfoQuery crmCustomerInfoQuery1 = new CrmCustomerInfoQuery();
            crmCustomerInfoQuery1.setIsPublic(true);
            crmCustomerInfoQuery1.setPageNo(crmCustomerInfoQuery.getPageNo());
            crmCustomerInfoQuery1.setPageSize(crmCustomerInfoQuery.getPageSize());
            crmCustomerInfoQuery1.setType(crmCustomerInfoQuery.getType());
            Page<CrmCustomerInfoListVO> crmCustomerInfoListVOPage = selectPage(crmCustomerInfoQuery, tokenUser.getSiteId());
            for (CrmCustomerInfoListVO entity : crmCustomerInfoListVOPage.getEntities()) {
                String phone = entity.getPhone();
                StringBuilder stringBuilder = new StringBuilder(phone);
                StringBuilder replace = stringBuilder.replace(3, 7, "****");
                entity.setPhone(replace.toString());
                //是否可以编辑
                if (!StringUtils.isEmpty(entity.getSourceUserId()) && entity.getSourceUserId().equals(tokenUser.getUserId())) {
                    entity.setIsEdit(true);
                } else {
                    entity.setIsEdit(false);
                }
            }
            return crmCustomerInfoListVOPage;
        } else if (!CollectionUtils.isEmpty(select) && select.get(0).getJurisdiction() == CrmMemberJurisdictionType.MANAGER.getValue().intValue()) {
            //所有客户经理
            CrmMemberQuery crmMemberQuery1 = new CrmMemberQuery();
            crmMemberQuery1.setJurisdiction(CrmMemberJurisdictionType.MANAGER.getValue());
            List<CrmMemberListVO> select1 = crmMemberService.select(crmMemberQuery1, tokenUser.getSiteId());
            for (CrmMemberListVO crmMemberListVO : select1) {
                memberIdList.add(crmMemberListVO.getId());
            }
            //自己下属
            CrmMemberRelationQuery crmMemberRelationQuery = new CrmMemberRelationQuery();
            crmMemberRelationQuery.setSuperiorMemberId(select.get(0).getId());
            List<CrmMemberRelationListVO> select2 = crmMemberRelationService.select(crmMemberRelationQuery, tokenUser.getSiteId());
            for (CrmMemberRelationListVO crmMemberRelationListVO : select2) {
                memberIdList.add(crmMemberRelationListVO.getMemerId());
            }
            crmCustomerInfoQuery.setMemberIdList(memberIdList);
        } else if (select.get(0).getJurisdiction() == CrmMemberJurisdictionType.EXECUTIVEDIRECTOR.getValue().intValue()) {
            crmCustomerInfoQuery.setMemberId(select.get(0).getId());
        }
        return selectPage(crmCustomerInfoQuery, tokenUser.getSiteId());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public void getTimeOutCustomers() {
        //最后访客时间超过7天的都移至公海
        List<CrmCustomerInfoVO> timeOutCustomers = crmCustomerInfoDAO.getTimeOutCustomers();
        if (!timeOutCustomers.isEmpty()) {
            for (CrmCustomerInfoVO crmCustomerInfoVO : timeOutCustomers) {
                //查询当前客户的所属是否客户主管
                if (StringUtils.isEmpty((crmCustomerInfoVO.getMemberId()))) {
                    continue;
                }
                //查询身份
                CrmMemberVO crmMemberVO = crmMemberService.selectByIdNotSiteId(crmCustomerInfoVO.getMemberId());
                if (crmMemberVO == null || crmMemberVO.getId() == null || crmMemberVO.getJurisdiction() == 1) {
                    continue;
                }
                //操作记录
                CrmOperationRecordAddDTO crmOperationRecordAddDTO = new CrmOperationRecordAddDTO();
                crmOperationRecordAddDTO.setCustomerId(crmCustomerInfoVO.getId());
                crmOperationRecordAddDTO.setRecordInfo(crmCustomerInfoVO.getMemberName() + "的" + crmCustomerInfoVO.getName() + "客户已被回收至公海");
                TokenUser tokenUser = new TokenUser();
                tokenUser.setSiteId(crmCustomerInfoVO.getSiteId());
                tokenUser.setUserId(crmCustomerInfoVO.getCreateUserId());
                crmOperationRecordService.save(crmOperationRecordAddDTO, tokenUser);
                //移至公海
                crmCustomerInfoDAO.removeToPublic(crmCustomerInfoVO.getId());
                //分配记录
                CrmCustomerDistributionRecordAddDTO crmCustomerDistributionRecordAddDTO = new CrmCustomerDistributionRecordAddDTO();
                crmCustomerDistributionRecordAddDTO.setCustomerId(crmCustomerInfoVO.getId());
                crmCustomerDistributionRecordAddDTO.setDistributionInfo("被回收至公海");
                crmCustomerDistributionRecordService.save(crmCustomerDistributionRecordAddDTO, UserContext.getUser());
            }
        }

    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public Integer batchDistribution(CrmCustomerInfoUpdateDTO crmCustomerInfoUpdateDTO, TokenUser tokenUser) {
        if (ArrayUtil.isEmpty(crmCustomerInfoUpdateDTO.getCustomerIds())) {
            throw new ParamException("客户数组为空");
        }
        List<String> strings = Arrays.asList(crmCustomerInfoUpdateDTO.getCustomerIds());
        strings.forEach((customerId) -> {
            crmCustomerInfoUpdateDTO.setDistributeOrGetTime(new Date());
            crmCustomerInfoUpdateDTO.setUserId(tokenUser.getUserId());
            crmCustomerInfoUpdateDTO.setDistributeName(tokenUser.getUserName());
            if (!StringUtils.isEmpty(crmCustomerInfoUpdateDTO.getMemberId())) {
                //分配
                crmCustomerInfoUpdateDTO.setSourceType(1);
                CrmCustomerDistributionRecordAddDTO crmCustomerDistributionRecordAddDTO = new CrmCustomerDistributionRecordAddDTO();
                crmCustomerDistributionRecordAddDTO.setCustomerId(customerId);
                crmCustomerDistributionRecordAddDTO.setDistributionInfo("由" + tokenUser.getUserName() + "分配给" + crmCustomerInfoUpdateDTO.getMemberName());
                crmCustomerDistributionRecordAddDTO.setDistributionReason(crmCustomerInfoUpdateDTO.getRemoveReason());
                crmCustomerDistributionRecordService.save(crmCustomerDistributionRecordAddDTO, tokenUser);
            } else {
                //领取
                CrmMemberQuery crmMemberQuery = new CrmMemberQuery();
                crmMemberQuery.setUserId(tokenUser.getUserId());
                List<CrmMemberListVO> select = crmMemberService.select(crmMemberQuery, tokenUser.getSiteId());
                if (!CollectionUtils.isEmpty(select)) {
                    crmCustomerInfoUpdateDTO.setSourceType(3);
                    crmCustomerInfoUpdateDTO.setMemberId(select.get(0).getId());
                    crmCustomerInfoUpdateDTO.setMemberName(tokenUser.getUserName());
                    CrmCustomerInfoVO crmCustomerInfoVO = selectById(customerId, tokenUser.getSiteId());
                    CrmOperationRecordAddDTO crmOperationRecordAddDTO = new CrmOperationRecordAddDTO();
                    crmOperationRecordAddDTO.setCustomerId(customerId);
                    crmOperationRecordAddDTO.setOperationName(tokenUser.getUserName());
                    crmOperationRecordAddDTO.setOperationType(CrmOperationType.GET.getValue());
                    crmOperationRecordAddDTO.setRecordInfo(tokenUser.getUserName() + "领取" + crmCustomerInfoVO.getName() + "客户");
                }

            }
            crmCustomerInfoUpdateDTO.setId(customerId);
            updateByIdSelective(crmCustomerInfoUpdateDTO.to(CrmCustomerInfoDO.class), tokenUser.getSiteId(), tokenUser.getUserId());
        });
        return 1;
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public CrmCustomerInfoVO save(CrmCustomerInfoAddDTO crmCustomerInfoAddDTO, TokenUser tokenUser) {

        // 转DO
        CrmCustomerInfoDO crmCustomerInfoDO = crmCustomerInfoAddDTO.to(CrmCustomerInfoDO.class);
        // 保存
        crmCustomerInfoDO = save(crmCustomerInfoDO, tokenUser.getSiteId(), tokenUser.getUserId());

        return crmCustomerInfoDO.to(CrmCustomerInfoVO.class);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int update(CrmCustomerInfoUpdateDTO crmCustomerInfoUpdateDTO, TokenUser tokenUser) {
        checkRepeat(crmCustomerInfoUpdateDTO.to(CrmCustomerInfoDO.class), tokenUser);
        CrmCustomerInfoVO crmCustomerInfoVO = selectById(crmCustomerInfoUpdateDTO.getId(), tokenUser.getSiteId());
        Boolean aBoolean = crmMemberService.permissionVerification(tokenUser, 1);
        //是否为更改签约客户
        if ((crmCustomerInfoUpdateDTO.getIsSign() != null)) {
            if (crmCustomerInfoUpdateDTO.getIsSign() || crmCustomerInfoUpdateDTO.getContract() != null
                    || crmCustomerInfoUpdateDTO.getContractStartTime() != null
                    || crmCustomerInfoUpdateDTO.getContractEndTime() != null
                    || crmCustomerInfoUpdateDTO.getBusinessLicense() != null
                    || crmCustomerInfoUpdateDTO.getCooperativeProducts() != null) {
                crmCustomerInfoUpdateDTO.setType(2);
                crmCustomerInfoUpdateDTO.setSigningTime(new Date());
                CrmCustomerDistributionRecordAddDTO crmCustomerDistributionRecordAddDTO = new CrmCustomerDistributionRecordAddDTO();
                crmCustomerDistributionRecordAddDTO.setCustomerId(crmCustomerInfoUpdateDTO.getId());
                crmCustomerDistributionRecordAddDTO.setDistributionInfo("由" + tokenUser.getUserName() + "变更为签约客户");
                crmCustomerDistributionRecordService.save(crmCustomerDistributionRecordAddDTO, tokenUser);
            }
        } else
            //是否为移至公海
            if (crmCustomerInfoUpdateDTO.getIsPublic() != null && crmCustomerInfoUpdateDTO.getIsPublic()) {
                CrmCustomerDistributionRecordAddDTO crmCustomerDistributionRecordAddDTO = new CrmCustomerDistributionRecordAddDTO();
                crmCustomerDistributionRecordAddDTO.setCustomerId(crmCustomerInfoUpdateDTO.getId());
                crmCustomerDistributionRecordAddDTO.setDistributionInfo("由" + tokenUser.getUserName() + "移至公海");
                crmCustomerDistributionRecordAddDTO.setDistributionReason(crmCustomerInfoUpdateDTO.getRemoveReason());
                crmCustomerDistributionRecordService.save(crmCustomerDistributionRecordAddDTO, tokenUser);
            } else if (!StringUtils.isEmpty(crmCustomerInfoUpdateDTO.getMemberId())) {
                if (!aBoolean) {
                    //throw new ParamException("没有分配客户的权限");
                }
                //是否为分配
                crmCustomerInfoUpdateDTO.setSourceType(1);
                crmCustomerInfoUpdateDTO.setDistributeOrGetTime(new Date());
                crmCustomerInfoUpdateDTO.setDistributeName(tokenUser.getUserName());
                CrmCustomerDistributionRecordAddDTO crmCustomerDistributionRecordAddDTO = new CrmCustomerDistributionRecordAddDTO();
                crmCustomerDistributionRecordAddDTO.setCustomerId(crmCustomerInfoUpdateDTO.getId());
                crmCustomerDistributionRecordAddDTO.setDistributionInfo("由" + tokenUser.getUserName() + "分配至" + crmCustomerInfoUpdateDTO.getMemberName());
                crmCustomerDistributionRecordService.save(crmCustomerDistributionRecordAddDTO, tokenUser);

                CrmOperationRecordAddDTO crmOperationRecordAddDTO = new CrmOperationRecordAddDTO();
                crmOperationRecordAddDTO.setCustomerId(crmCustomerInfoUpdateDTO.getId());
                crmOperationRecordAddDTO.setOperationName(tokenUser.getUserName());
                crmOperationRecordAddDTO.setOperationType(CrmOperationType.CHANGE.getValue());
                crmOperationRecordAddDTO.setRecordInfo(tokenUser.getUserName() + "将" + crmCustomerInfoVO.getName() + "分配给" + crmCustomerInfoUpdateDTO.getName());
                crmOperationRecordService.save(crmOperationRecordAddDTO, tokenUser);
            } else if (crmCustomerInfoUpdateDTO.getOperationType() != null && crmCustomerInfoUpdateDTO.getOperationType() == 3) {
                //领取客户
                crmCustomerInfoUpdateDTO.setDistributeOrGetTime(new Date());
                crmCustomerInfoUpdateDTO.setDistributeName(tokenUser.getUserName());
                crmCustomerInfoUpdateDTO.setSourceType(3);
                crmCustomerInfoUpdateDTO.setIsPublic(false);
                CrmOperationRecordAddDTO crmOperationRecordAddDTO = new CrmOperationRecordAddDTO();
                crmOperationRecordAddDTO.setCustomerId(crmCustomerInfoUpdateDTO.getId());
                crmOperationRecordAddDTO.setOperationName(tokenUser.getUserName());
                crmOperationRecordAddDTO.setOperationType(CrmOperationType.GET.getValue());
                crmOperationRecordAddDTO.setRecordInfo(tokenUser.getUserName() + "领取" + crmCustomerInfoUpdateDTO.getName() + "客户");
                crmOperationRecordService.save(crmOperationRecordAddDTO, tokenUser);
            } else {
                //添加更改客户操作记录
                CrmOperationRecordAddDTO crmOperationRecordAddDTO = new CrmOperationRecordAddDTO();
                crmOperationRecordAddDTO.setCustomerId(crmCustomerInfoUpdateDTO.getId());
                crmOperationRecordAddDTO.setOperationName(tokenUser.getUserName());
                crmOperationRecordAddDTO.setOperationType(CrmOperationType.UPDATE.getValue());
                crmOperationRecordAddDTO.setRecordInfo("修改" + crmCustomerInfoVO.getName() + "客户");
                crmOperationRecordService.save(crmOperationRecordAddDTO, tokenUser);
            }
        //转DO
        CrmCustomerInfoDO crmCustomerInfoDO = crmCustomerInfoUpdateDTO.to(CrmCustomerInfoDO.class);
        //根据主键更新，只更新非null值
        return updateByIdSelective(crmCustomerInfoDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    /**
     * 校验重复性
     *
     * @param crmCustomerInfoDO do
     */
    private void checkRepeat(CrmCustomerInfoDO crmCustomerInfoDO, TokenUser tokenUser) {
        List<CrmCustomerInfoListVO> select = new ArrayList<>();
        if (!StringUtils.isEmpty(crmCustomerInfoDO.getCompanyName()) && !StringUtils.isEmpty(crmCustomerInfoDO.getCompanyAddress())) {
            CrmCustomerInfoQuery crmCustomerInfoQuery = new CrmCustomerInfoQuery();
            crmCustomerInfoQuery.setCompanyName(crmCustomerInfoDO.getCompanyName());
            crmCustomerInfoQuery.setCompanyAddress(crmCustomerInfoDO.getCompanyAddress());
            select = select(crmCustomerInfoQuery, tokenUser.getSiteId());
            if (ObjectUtil.isNotNull(crmCustomerInfoDO.getId())) {
                select = select.parallelStream().filter(crmCustomerInfoListVO -> !crmCustomerInfoListVO.getId().equals(crmCustomerInfoDO.getId())).collect(Collectors.toList());
            }
            if (!CollectionUtils.isEmpty(select)) {
                throw new ParamException("已创建该客户");
            }
        }
        if (!StringUtils.isEmpty(crmCustomerInfoDO.getProductName()) && !StringUtils.isEmpty(crmCustomerInfoDO.getEntryName())) {
            CrmCustomerInfoQuery crmCustomerInfoQuery1 = new CrmCustomerInfoQuery();
            crmCustomerInfoQuery1.setProductName(crmCustomerInfoDO.getProductName());
            crmCustomerInfoQuery1.setEntryName(crmCustomerInfoDO.getEntryName());
            select = select(crmCustomerInfoQuery1, tokenUser.getSiteId());
            if (ObjectUtil.isNotNull(crmCustomerInfoDO.getId())) {
                select = select.parallelStream().filter(crmCustomerInfoListVO -> !crmCustomerInfoListVO.getId().equals(crmCustomerInfoDO.getId())).collect(Collectors.toList());
            }
            if (!CollectionUtils.isEmpty(select)) {
                throw new ParamException("该项目下已存在相同的产品");
            }
        }
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, String... crmCustomerInfoIds) {
        return logicalDeleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), (Object[]) crmCustomerInfoIds);
    }


    @Override
    public CrmCustomerInfoVO selectById(String crmCustomerInfoId, String siteId) {
        CrmCustomerInfoDO crmCustomerInfoDO = selectDOById(crmCustomerInfoId, siteId);
        if (crmCustomerInfoDO == null) {
            return null;
        }
        return crmCustomerInfoDO.to(CrmCustomerInfoVO.class);
    }

    @Override
    public List<CrmCustomerInfoListVO> select(CrmCustomerInfoQuery crmCustomerInfoQuery, String siteId) {
        List<CrmCustomerInfoDO> crmCustomerInfoDOList = selectDO(crmCustomerInfoQuery, siteId);
        if (CollectionUtils.isEmpty(crmCustomerInfoDOList)) {
            return crmCustomerInfoDOList == null ? null : new ArrayList<>();
        }
        return crmCustomerInfoDOList.stream()
                .map(crmCustomerInfoDO -> crmCustomerInfoDO.to(CrmCustomerInfoListVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public int selectCount(CrmCustomerInfoQuery crmCustomerInfoQuery, String siteId) {
        Example example = buildExample(crmCustomerInfoQuery, siteId);
        return crmCustomerInfoDAO.selectCountByExample(example);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public Page<CrmCustomerInfoListVO> selectPage(CrmCustomerInfoQuery crmCustomerInfoQuery, String siteId) {
        Example example = buildExample(crmCustomerInfoQuery, siteId);
        Page<CrmCustomerInfoDO> page = crmCustomerInfoDAO.selectPageByExample(example,
                crmCustomerInfoQuery.getPageNo(),
                crmCustomerInfoQuery.getPageSize());
        return page.to(CrmCustomerInfoListVO.class);
    }

    @Override
    public CrmCustomerInfoDO selectDOById(String crmCustomerInfoId, String siteId) {
        return listById(crmCustomerInfoId, siteId);
    }

    @Override
    public List<CrmCustomerInfoDO> selectDO(CrmCustomerInfoQuery crmCustomerInfoQuery, String siteId) {
        Example example = buildExample(crmCustomerInfoQuery, siteId);
        return crmCustomerInfoDAO.selectByExample(example);
    }


    /**
     * 根据查询参数，构建example
     *
     * @param crmCustomerInfoQuery 查询参数
     * @param siteId               所属站点id
     * @return example
     */
    private Example buildExample(CrmCustomerInfoQuery crmCustomerInfoQuery, String siteId) {
        Example example = new Example(CrmCustomerInfoDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        if (!StringUtils.isEmpty(crmCustomerInfoQuery.getBaseGet())) {
            example.and().andLike("name", "%" + crmCustomerInfoQuery.getBaseGet() + "%")
                    .orLike("phone", "%" + crmCustomerInfoQuery.getBaseGet() + "%")
                    .orLike("companyName", "%" + crmCustomerInfoQuery.getBaseGet() + "%")
                    .orLike("sourceName", "%" + crmCustomerInfoQuery.getBaseGet() + "%")
                    .orLike("distributeName", "%" + crmCustomerInfoQuery.getBaseGet() + "%");
        }
        if (crmCustomerInfoQuery.getType() != null) {
            example.and().andEqualTo("type", crmCustomerInfoQuery.getType());
        }
        if (crmCustomerInfoQuery.getSourceType() != null) {
            example.and().andEqualTo("sourceType", crmCustomerInfoQuery.getSourceType());
        }
        if (!StringUtils.isEmpty(crmCustomerInfoQuery.getMemberName())) {
            example.and().andLike("memberName", "%" + crmCustomerInfoQuery.getMemberName() + "%");
        }
        if (crmCustomerInfoQuery.getDistributeOrGetTimeStart() != null && crmCustomerInfoQuery.getDistributeOrGetTimeEnd() != null) {
            Date startDate = DateUtil.parse(crmCustomerInfoQuery.getDistributeOrGetTimeStart(), "yyyy-MM-dd");
            Date endDate = DateUtil.parse(crmCustomerInfoQuery.getDistributeOrGetTimeEnd(), "yyyy-MM-dd");
            example.and().andGreaterThanOrEqualTo("distributeOrGetTime", startDate)
                    .andLessThanOrEqualTo("distributeOrGetTime", endDate);
        }
        if (crmCustomerInfoQuery.getSignTimeStart() != null && crmCustomerInfoQuery.getSignTimeEnd() != null) {
            Date startDate = DateUtil.parse(crmCustomerInfoQuery.getSignTimeStart(), "yyyy-MM-dd");
            Date endDate = DateUtil.parse(crmCustomerInfoQuery.getSignTimeEnd(), "yyyy-MM-dd");
            example.and().andGreaterThanOrEqualTo("signingTime", startDate)
                    .andLessThanOrEqualTo("signingTime", endDate);
        }
        if (crmCustomerInfoQuery.getVisitTimeStart() != null && crmCustomerInfoQuery.getVisitTimeEnd() != null) {
            Date startDate = DateUtil.parse(crmCustomerInfoQuery.getVisitTimeStart(), "yyyy-MM-dd");
            Date endDate = DateUtil.parse(crmCustomerInfoQuery.getVisitTimeEnd(), "yyyy-MM-dd");
            example.and().andGreaterThanOrEqualTo("lastVisitTime", startDate)
                    .andLessThanOrEqualTo("lastVisitTime", endDate);
        }
        if (!CollectionUtils.isEmpty(crmCustomerInfoQuery.getMemberIdList())) {
            example.and().andIn("memberId", crmCustomerInfoQuery.getMemberIdList());

        } else if (!StringUtils.isEmpty(crmCustomerInfoQuery.getMemberId())) {
            example.and().andEqualTo("memberId", crmCustomerInfoQuery.getMemberId());
        }
        if (crmCustomerInfoQuery.getIsPublic() != null) {
            example.and().andEqualTo("isPublic", crmCustomerInfoQuery.getIsPublic());
        }
        if (!StringUtils.isEmpty(crmCustomerInfoQuery.getCompanyName())) {
            example.and().andEqualTo("companyName", crmCustomerInfoQuery.getCompanyName());
        }
        if (!StringUtils.isEmpty(crmCustomerInfoQuery.getCompanyAddress())) {
            example.and().andEqualTo("companyAddress", crmCustomerInfoQuery.getCompanyAddress());
        }
        if (!StringUtils.isEmpty(crmCustomerInfoQuery.getProductName())) {
            example.and().andEqualTo("productName", crmCustomerInfoQuery.getProductName());
        }
        if (!StringUtils.isEmpty(crmCustomerInfoQuery.getEntryName())) {
            example.and().andEqualTo("entryName", crmCustomerInfoQuery.getEntryName());
        }
        if (!StringUtils.isEmpty(crmCustomerInfoQuery.getBaseGet())) {
            example.and().orLike("name", "%" + crmCustomerInfoQuery.getBaseGet() + "%").orLike("phone", "%" + crmCustomerInfoQuery.getBaseGet() + "%")
                    .orLike("companyName", "%" + crmCustomerInfoQuery.getBaseGet() + "%")
                    .orLike("distributeName", "%" + crmCustomerInfoQuery.getBaseGet() + "%");
        }
        // if(!StringUtils.isEmpty(crmCustomerInfoQuery.get))


        // 排序
        ExampleKit.setExampleOrder(example, crmCustomerInfoQuery.getOrders());
        return example;
    }
}




